<!--
*@Author: QWP
*@Description: 车辆年检
*@Params: pType  1  录入页面       2 维修分析页面        3 保养
*@Date 2024-09-18 12:23
-->
<template>
  <a-layout class="f-h-100">
    <u-table-header
      class="s-bg-white">
      <u-form :model="state.searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="initPage(1)">
        <a-col>
          <a-space>
            <u-icon-button itype="search" native-type="submit"  @click="initPage(1)" >
              查询
            </u-icon-button>
            <u-icon-button itype="export"  @click="exportBtn"  v-if="route.params.pType == 1">
              导出
            </u-icon-button>
          </a-space>
        </a-col>
        <a-col flex="1" v-if="route.params.pType == 1">
          <a-row justify="end">
            <a-space>
              <u-icon-button itype="add" @click="toEdit">
                新增
              </u-icon-button>
              <u-icon-button itype="edit" @click="toEdit(2)">
                修改
              </u-icon-button>
              <u-icon-button @click="deleteBtn" itype="delete" type="danger">
                删除
              </u-icon-button>
            </a-space>
          </a-row>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content>
      <u-table :columns="state.columns"
        :data="state.tabData"
        v-model:pagination="pagenation"
        :loading="loading"
        :scroll="{ y: useTableScroll() }"
        @onDblclick="(record) => {
          if(route.params.pType == 2) {
            return
          }
          state.keyid = record.keyid;
          state.showEdit = true;
        }"
        @onSelect="({ selectedRows }) => state.tabSelData.splice(0, state.tabSelData.length, ...selectedRows)"
        @change="getSearch"
      />
    </u-table-content>
    
    <!-- 新增编辑 -->
    <Edit
      v-model:open="state.showEdit"
      :title="route.params.pType == 1 ? '年检编辑' : '年检信息'"
      :keyid="state.keyid"
      wrap-class-name="full-modal"
      @success="state.keyid = '', state.showEdit = false, getSearch()"
      @close="state.keyid = ''"
    />
  </a-layout>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch, onActivated } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave} from "vue-router";
import { useBaseStore, useLoginStore } from '@/store'
import { storeToRefs } from "pinia";
import Edit from "./Edit.vue";
import { formtTableEnum, getItemByIds } from "@/util/format.ts"
import { alertC, confirmC, nullC, numberC, isValue, jsonCopy, messageC } from "@/util/common";
import dayjs from "dayjs";
import { _IFormEl } from "@/components/common/form/interface";
import { ColProps, FormItemProps, TableColumnProps } from "ant-design-vue";
import { useTableScroll } from '@/hooks/useTable'
import { formatEmergency } from '@/views/oa/officialDoc/dispatch/emergencyTool.ts'
import * as checkApi from '@/service/administration/yearCheck'

const route = useRoute();
const { APPLICATION_TYPE, APP_STATUS } = storeToRefs(useBaseStore())

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`
})
const formItemProps = {
  labelWidth: '60px',
  style: {
    width: '300px'
  }
};
const searchEl  = [
  { label: "关键字", key: "keywords", element: "input", 
    formItemProps: formItemProps, 
    componentProps: { placeholder: '车牌号、部门、年检机构' }
  },
];

const loading = ref<boolean>(false)

const state = reactive({
  searchF: {
    model: {
      keywords: null,
      status: "",
    },
    current: 1,
    size: 20,
  },
  total: 0,
  loading: false,
  tabData: [],
  tabSelData: [],
  columns: [
    { type: "index", align: "center", title: "序号", width: 50, 
      customRender: ({ index }) => index += 1
    },

     ...(route.params.pType == 1 ? [
      { title: "申请时间", width: 160, dataIndex: "applicationdate", align: "center", 
        customRender: ({ text }) =>(text || '').split(' ')[0]
      },
    ] : []),

    { title: "车牌号", width: 120, dataIndex: "vehiclenumber", align: "center", },
    { title: "车辆所属部门", width: 120, dataIndex: "ssdeptname", align: "center", },

    ...(route.params.pType == 1 ? [
      { title: "申请人", width: 120, dataIndex: "applicantname", align: "center", },
      { title: "申请人电话", width: 140, dataIndex: "applicantphone", align: "center", },
    ] : []),
    
    { title: "年检机构", minWidth: 200, dataIndex: "fkmechanismname",},
    { title: "年检事由", minWidth: 200, dataIndex: "inspectionreason",},
    { title: "年检完成时间", width: 160, dataIndex: "actualcomdate", align: "center", 
      customRender: ({ text }) =>(text || '').split(' ')[0]
    },
    
    ...(route.params.pType == 2 ? [
      { title: "距下次年检天数", width: 120, dataIndex: "day", align: "center", 
        customRender: ({ record }) => {
          return nextToNowDays(record.actualcomdate)
        }
      },
    ] : []),
  ],

  showEdit: false,
  keyid: "",
  cphData: [],
  lyData: [],
  auditData: [],
})

onMounted(() => {
  initPage()
})

onActivated(() => {
  initPage()
})

// 初始化页面
const initPage = (current?: number) => {
  if(route.params.pType == 1) {
    state.searchF.model.pageType = 1
    getSearch(current);
  } else if(route.params.pType == 2) {
    state.searchF.model.applicationtype = 3
    getInspectionReport(current)
  }
}

// 列表查询
async function getSearch(current?: number) {
  if (current == 1) {
    pagenation.current = current;
  }

  state.searchF.size = pagenation.pageSize
  state.searchF.current = pagenation.current

  loading.value = true;
  checkApi.search(state.searchF).then((res) => {
    loading.value = false;
    if (res.code == 0) {
      state.tabData = res.data.records;
      pagenation.total = res.data.total;
    }
  })
  .catch(() => loading.value = false);
}

// 列表查询
async function getInspectionReport(current?: number) {
  if (current == 1) {
    pagenation.current = current;
  }

  state.searchF.size = pagenation.pageSize
  state.searchF.current = pagenation.current

  loading.value = true;
  checkApi.inspectionReport(state.searchF).then((res) => {
    loading.value = false;
    if (res.code == 0) {
      state.tabData = res.data.records;
      pagenation.total = res.data.total;
    }
  })
  .catch(() => loading.value = false);
}

// 新增、修改
function toEdit(type?: number) {
  if(type == 2) {
    if (state.tabSelData.length !== 1) {
      messageC("能且只能选择一条数据");
      return;
    }
    state.keyid = state.tabSelData[0].keyid;
  }
  state.showEdit = true;
}

// 删除
async function deleteBtn() {
  if (state.tabSelData.length == 0) {
    messageC("请先选择要删除的数据!", "warning");
    return;
  }
  await alertC("确认删除选中的数据?", "confirm")
  
  loading.value = true;
  try {
    let ids = state.tabSelData.map((item) => item.keyid);
    const res = await checkApi.del({ ids: ids.join(",") })
    if (res.code == 0) {
      getSearch();
      messageC(res.msg, "success");
    } else {
      messageC(res.msg, "warning");
    }
  } catch (error) {}
  loading.value = false
}

// 计算下一次购买日局现在的天数
function nextToNowDays(nextDate: any) {
  if(nextDate) {
    let deadDay = dayjs(nextDate).add(1, 'year').subtract(1, 'day').diff(dayjs(), 'day') + 1
    let deadDay1 = deadDay < 0 ? `已超期${ Math.abs(deadDay) }` : deadDay
    return deadDay <= 30 ? formatEmergency(4, `${deadDay1}天`) : `${deadDay1}天`
  }
}

// 导出
async function exportBtn() {
  loading.value = true;
  try {
    const res = await checkApi.download({ ...state.searchF, size: -1, filename: "车辆年检信息" })
  } catch (error) { }
  loading.value = false;
}
</script>
<style lang="scss"></style>
